package client

import (
	"fmt"
	"net"

	. "gitee.com/ezios/file-assistant/core"
)

type Client struct {
	Host string
	Port int
	Conn net.Conn
}

// 创建客户端
func NewClient(host string, port int) *Client {

	return &Client{
		Host: host,
		Port: port,
	}
}

// 连接服务器
func (c *Client) Connect() {
	remote := net.TCPAddr{
		IP:   net.ParseIP(c.Host),
		Port: c.Port,
	}
	tcpConn, err := net.DialTCP("tcp", nil, &remote)
	if err != nil {
		panic(err)
	}
	c.Conn = tcpConn
}

// 发送消息
func (c *Client) Send(message *Message) {
	data, _ := message.ToJson()
	c.Conn.Write(data)
}

func (c *Client) Work(transferFile *TransferFile) {
	c.Connect()
	defer c.Conn.Close()
	defer transferFile.Close()

	// 连接服务器
	message := ConnectionMessage()
	c.Send(&message)

	// 读取服务器返回的消息
	buf := make([]byte, 1024)
	n, err := c.Conn.Read(buf)
	if err != nil {
		panic(err)
	}
	message = ParseFromJson(buf[:n])
	if message.Code != MESSAGE_CONN {
		fmt.Println("服务器响应异常")
		panic("服务器响应异常")
	}
	fmt.Println("连接就绪")

	// 传递文件信息
	message = FileMessage(*transferFile)
	c.Send(&message)
	n, err = c.Conn.Read(buf)
	if err != nil {
		panic(err)
	}
	message = ParseFromJson(buf[:n])
	if message.Code != MESSAGE_FILE {
		fmt.Println("服务器响应异常",message)
		panic("服务器响应异常")
	}
	fmt.Println("开始发送")

	// 发送文件
	for {
		n, err = transferFile.Read(buf)
		if err != nil {
			if(err.Error() != "EOF"){
				panic(err)
			}
			fmt.Println("发送完毕")
			break
		}
		_ , err = c.Conn.Write(buf)
		if err != nil {
			panic(err)
		}
		if n == 0 {
			break
		}
	}

}
